package me.yangbajing.web

import net.liftweb.http.{RedirectResponse, S, SessionVar, RequestVar}
import net.liftweb.common._
import net.liftweb.util.Helpers._
import net.liftweb.sitemap.Loc.TestAccess

import me.yangbajing.model._
import me.yangbajing.common.Tag
import me.yangbajing.model.Account
import net.liftweb.sitemap.Loc.TestAccess
import me.yangbajing.common.Tag
import net.liftweb.common.Full

object W extends Loggable {

  object reqTag extends RequestVar[Box[Tag]](_findTag("tag_id"))

  object reqCategory extends RequestVar[Box[MCategory]](_findCategory("category_id"))

  object reqDocument extends RequestVar[Box[MDocument]](_findDocument("document_id"))

  object reqUser extends RequestVar[Box[MUser]](_findUser("user_id"))

  object theAccount extends SessionVar[Box[Account]](Empty)

  def testSession = TestAccess(
    () => {
      val result =
        for {
          account <- theAccount.is
        } yield account

      result match {
        case Full(account) =>
          Empty

        case Failure("no site", _, _) =>
          Full(RedirectResponse("/404"))

        case _ =>
          val uri = S.uriAndQueryString openOr S.uri
          val gotoPage =
            if (uri.startsWith("/index") || uri == "/") ""
            else "?goto_page=" + urlEncode(uri)

          Full(RedirectResponse("/h/user/sign_in" + gotoPage))
      }
    })

  def signOut = TestAccess(
    () => {
      W.theAccount.remove()
      Full(RedirectResponse("/index"))
    })

  def saveSessionAndCookie(user: MUser, remember: Boolean): Account = {
    val account = Account(user.id, user)

    // TODO 保存cookie
    // ......

    theAccount(Full(account))
    account
  }

  def hrefUser(id: String): String =
    "/user/" + urlEncode(id)

  def hrefTag(): String =
    "/tag"

  def hrefTag(tagId: String): String =
    "/tag/" + urlEncode(tagId)

  def hrefDocument(): String =
    "/doc"

  def hrefDocumentEdit(id: String): String =
    "/doc/%s/edit" format urlEncode(id)

  def hrefDocument(id: String): String =
    "/doc/" + urlEncode(id)

  def hrefDocumentNew(): String =
    "/doc/new"

  def hrefCategory(): String =
    "/category"

  def hrefCategory(id: String): String =
    s"/category/${urlEncode(id)}"

  private def _findTag(id: String): Box[Tag] =
    for {
      tagId <- H.param(id)
      tag <- MTag.findOne(tagId)
    } yield tag

  private def _findCategory(id: String): Box[MCategory] =
    for {
      categoryId <- H.param(id)
      category <- MCategory.findOne(categoryId)
    } yield category

  private def _findDocument(id: String): Box[MDocument] =
    for {
      docId <- H.param(id)
      doc <- MDocument.findOne(docId)
    } yield doc

  private def _findUser(id: String): Box[MUser] =
    for {
      userId <- H.param(id)
      user <- MUser.findOne(userId)
    } yield user

}
